const fs = require('fs');

const ws = fs.createWriteStream('./test.txt');

const id = setInterval(() => {
  const num = parseInt(Math.random() * 10);
  if (num < 9) {
    // 仅支持写入Buffer或字符串
    ws.write(num + '');
  } else {
    clearInterval(id);
    // 先清掉循环写操作
    // 避免报出write after end 异常
    // end将write在缓存的数据一次性写到目标文件
    // 并且关闭管道
    // 同时发射一个finish事件
    ws.end();
  }
}, 200);

ws.on('finish', () => {
  console.log('wrote into file successfully');
});